import { useEffect } from 'react';
import { useContext } from 'react';
import { createContext, useReducer } from 'react';

const MyContext = createContext()

const initialState = {
  bannerList: [],
  proList: []
}

const reducer = (state, action) => {
  const { type, payload } = action
  switch (type) {
    case 'CHANGE_BANNER_LIST':
      return Object.assign({}, state, { bannerList: payload })
    case 'CHANGE_PRO_LIST':
      return { ...state, proList: payload }
    default:
      return state
  }

}

const Child1 = () => {
  const { state, dispatch } = useContext(MyContext)
  useEffect(() => {
    fetch('http://121.89.205.189:3001/api/pro/list?limitNum=15')
      .then(res => res.json())
      .then(res => {
        dispatch({ type: 'CHANGE_PRO_LIST', payload: res.data })
      })
  }, [dispatch])
  return (
    <div>
      {
        state.proList && state.proList.map(item => {
          return (<p key = { item.proid }>{ item.proname }</p>)
        })
      }
    </div>
  )
}
const Child2 = () => {
  const { state } = useContext(MyContext)
 
  return (
    <div>
      {
        state.proList && state.proList.map(item => {
          return (<p key = { item.proid }>{ item.proname }</p>)
        })
      }
    </div>
  )
}

const App = () => {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <MyContext.Provider value={ { state, dispatch } }>
      <Child1 />
      <hr />
      <Child2 />
    </MyContext.Provider>
  );
}

export default App;